package com.itheima.reggie.filter;


import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    private AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // request与response强制转化成子类，方便调用子类的方法
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 获取请求的路由
        String requestURI = request.getRequestURI();
        // 定义可放行的路由
        String[] urls = {"/backend/**","/front/**","/employee/login","/common/**","/user/sendMsg","/user/login"};
        // 判断请求理由是否在可放行路由中
        boolean flag = checkUrl(requestURI,urls);
        if(flag){
            //直接放行
            filterChain.doFilter(request,response);
            return;
        }
        // 判断请求路由session
        HttpSession session = request.getSession();
        if (session.getAttribute("employee") != null) {
            filterChain.doFilter(request,response);
            return;
        }

        //检查前台用户是否已经登录，如果已经的登录直接放行
        if(session.getAttribute("user")!=null){
            //如果用户已经登录，也可以直接放行
            filterChain.doFilter(request,response); //访问目标资源
            return;
        }

        // 返回前端信息
        String json = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(json);
    }

    public Boolean checkUrl(String requestURI, String[] urls){
        for (String url : urls) {
            if (antPathMatcher.match(url, requestURI)) {
                return true;
            }
        }
        return false;
    }
}
